package com.examiner.controller;

import com.examiner.bean.Do.RoleMenuDo;
import com.examiner.bean.Examiner;
import com.examiner.bean.Manager;
import com.examiner.bean.RoleMenu;
import com.examiner.page.QueryInfo;
import com.examiner.result.EmptyObject;
import com.examiner.result.Result;
import com.examiner.service.ExaminerService;
import com.examiner.service.RoleMenuService;
import com.examiner.token.JwtUtil;
import org.hibernate.Session;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@RestController
@RequestMapping("/examiner")
public class ExaminerController {

    @Resource
    private ExaminerService examinerService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private RoleMenuService roleMenuService;

    @PersistenceContext
    private EntityManager entityManager;

    // 登录
    @PostMapping("/login")
    public Result<Object> login(@RequestBody Examiner examiner, HttpServletResponse response){
        System.out.println(passwordEncoder.encode(examiner.getPassword()));
        Examiner person = examinerService.hasUserName(examiner.getUserName());
        if (person == null){return Result.RESULT(201,"登录失败",true,null); }
        boolean matches = passwordEncoder.matches(examiner.getPassword(), person.getPassword());
        if (!matches) return Result.RESULT(1003,"密码错误，登录失败",false,null);
        Session session = entityManager.unwrap(org.hibernate.Session.class);
        session.evict(person);
        // 返回 token
        Map<String, Object> claims = new HashMap<>();
        claims.put("userName",person.getUserName());
        claims.put("role",person.getRole());
        String token = JwtUtil.createJWT(UUID.randomUUID().toString(), "examiner", null, claims);
        response.addHeader("token",token);
        List<RoleMenuDo> roleList = roleMenuService.getRoleList(person.getRole());
        // 返回当前用户信息
        person.setPassword("");
        Map<String, Object> data = new HashMap<>();
        data.put("user",person);
        data.put("token",token);
        data.put("roleList",roleList);
        return Result.RESULT(200,"登录成功",true,data);
    }
    // 根据用户名查信息

    /**
     * 分页查询列表
     * @param queryInfo
     * @return
     */
    @PostMapping("/getExaminerList")
    public Result<Object> getExaminerList(@RequestBody QueryInfo queryInfo){
        Map<String, Object> data = new HashMap<>();
        List<Examiner> examinerList =  examinerService.getExaminerList(queryInfo);
        int total = examinerService.getTotal(queryInfo.getQuery());
        data.put("total",total);
        data.put("examinerList",examinerList);
        return Result.SUCCESS(data);
    }

    @PostMapping("/getExaminerListByQuery")
    public Result<Object> getExaminerListByQuery(){
        Map<String, Object> data = new HashMap<>();
        List<Examiner> examinerList =  examinerService.getExaminerListByQuery("");
        for (Examiner examiner : examinerList) {
            examiner.setPassword("");
        }
        data.put("examinerList",examinerList);
        return Result.SUCCESS(data);
    }

    /**
     * 检查原密码是否正确
     * @param oldPassword
     * @return
     */
    @PostMapping("/checkPassword/{id}")
    public Result<EmptyObject> checkPassword(@PathVariable("id")Integer id,
                                             @RequestBody String oldPassword){
        Examiner one = examinerService.findOne(id);
        // 验证密码
        if (one == null){
            // 该用户不存在
            return Result.RESULT(1002,"该用户不存在",false,null);
        }
        // 验证密码是否正确
        boolean matches = passwordEncoder.matches(oldPassword,one.getPassword());
        if (!matches){
            return Result.RESULT(1003,"密码错误",false,null);
        }
        return Result.SUCCESS(EmptyObject.empty);
    }

    /**
     * 修改密码
     */
    @PostMapping("/updatePassword/{id}")
    public Result<EmptyObject> updatePassword(@PathVariable("id")Integer id,
                                              @RequestBody String newPassword){
        String encodePsw = passwordEncoder.encode(newPassword);
        Boolean aBoolean = examinerService.updateManagerPassword(id,encodePsw );
        if (!aBoolean) return Result.RESULT(1004,"修改密码失败",false,null);
        return Result.SUCCESS(EmptyObject.empty);
    }

    /* 修改 用户信息*/
    @PutMapping("/changeUserInfo")
    public Result<EmptyObject> updateManager(@RequestBody Examiner examiner){
        Examiner existById = examinerService.findOne(examiner.getId());
        // 判断该用户名是否被使用
        if (existById == null){
            return Result.RESULT(1002,"该用户名不存在",false,null);
        }
        if (!examiner.getPassword().equals(existById.getPassword())){
            examiner.setPassword(passwordEncoder.encode(examiner.getPassword()));
        }
        examinerService.saveExaminer(examiner);
        return Result.SUCCESS(EmptyObject.empty);
    }
    // 更改状态

    /**
     * 新增=
     * @param examiner
     * @return
     */
    @PostMapping("/addExaminer")
    public Result<EmptyObject> addManager(@RequestBody Examiner examiner){
        // 对密码进行加密
        examiner.setPassword(passwordEncoder.encode(examiner.getPassword()));
        examiner.setRole("examiner");
        examiner.setState(true);
        examinerService.saveExaminer(examiner);
        return Result.SUCCESS(EmptyObject.empty);
    }

    // 删除
    @DeleteMapping("/delExaminer/{id}")
    public Result<EmptyObject> deleteManager(@PathVariable("id")Integer id){
        examinerService.deleteManager(id);
        return Result.SUCCESS(EmptyObject.empty);
    }


}
